<template>
  <select class="select select-bordered input-md w-full max-w-xs min-w-48" v-model="selectedValue" @change="valueChanged()">
    <option :value="undefined" v-if="undefinedOption">{{undefinedOption}}</option>
    <option v-for="item in dataList" :value="item.id">{{ getSelectText(item) }}</option>
  </select>
</template>

<script setup>
import {httpGet} from "~/utils/http/http-helper.js";
import {notificationSuccess} from "../utils/notification/index.js";

const props = defineProps({
  modelValue: Number,
  undefinedOption: String,
  uri: String,
  textKey: String,
})
const dataList = ref([])
const selectedValue = ref()
selectedValue.value = props.modelValue

watch(() => props.modelValue, (newVal, oldVal) => {
  // 这里可以根据需要对父组件传递的值做出相应的处理
  selectedValue.value = newVal
})

const emit = defineEmits(['update:modelValue'])

onMounted(() => {
  loadData()
})

function valueChanged(){
  emit('update:modelValue', selectedValue.value)
}

function loadData(){
  httpGet(props.uri).then(resp => {
    if(!resp.success){
      notificationSuccess(resp.msg)
      return
    }
    dataList.value = resp.data
  })
}

function getSelectText(obj){
  const keys = Object.keys(obj)
  for(let i=0; i<keys.length; i++){
    if(keys[i] === props.textKey){
      return obj[props.textKey]
    }
  }
}

</script>

<style scoped>

</style>